package com.asktgapp.application;

import android.content.Context;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.architecture.retrofit.CustomGsonConverterFactory;
import com.asktgapp.modulebase.Constant;
import com.asktgapp.modulebase.ServiceUtil;
import com.asktgapp.modulebase.common.util.PreferencesUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * time:2018/1/4
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class TestApiUtil {
    private static final int DEFAULT_TIME_OUT = 5;//超时时间 5s
    private static final int DEFAULT_READ_TIME_OUT = 30;
    private Retrofit mRetrofit;
    public static final MediaType MULTIPART = MediaType.parse("multipart/form-data");


    private TestApiUtil() {
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间        builder.writeTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//读操作超时时间
        builder.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request.Builder requestBuilder = original.newBuilder();
                if (original.body() instanceof FormBody) {
                    FormBody.Builder newFormBody = new FormBody.Builder();
                    FormBody oidFormBody = (FormBody) original.body();
                    //循环遍历formBody添加原始数据,追加默认参数
                    for (int i = 0; i < oidFormBody.size(); i++) {
                        newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i));
                    }
                    String deviceId = Utils.getDeviceId(MyApplication.getInstance());
                    newFormBody.add("deviceId", deviceId);
                    newFormBody.add("platform", Constant.ANDROID_CHANNEL);
                    requestBuilder.method(original.method(), newFormBody.build());
                }
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }
        });

//        声明日志类
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
//设定日志级别
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//添加拦截器
        builder.addInterceptor(httpLoggingInterceptor);

        // 添加公共参数拦截器
        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(CustomGsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://shop.jg969.com:90/")
                .build();
    }


    //静态内部类实现单例:可以确保线程安全，也能够保证单例对象的唯一性，同时延迟了单例的实例化。
    public static TestApiUtil getInstance() {
        return SinglApiHolder.instance;
    }

    private static class SinglApiHolder {
        private static final TestApiUtil instance = new TestApiUtil();
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }

    public Apiservice create() {
        Apiservice apiService = mRetrofit.create(Apiservice.class);
        return apiService;
    }

    public static List<MultipartBody.Part> files2Parts(String key, Object[] filePaths, MediaType contentType) {
        List<MultipartBody.Part> parts = new ArrayList<>(filePaths.length);
        for (Object filePath : filePaths) {
            File file = new File((String) filePath);
            // 根据类型及File对象创建RequestBody（okhttp的类）
            RequestBody requestBody = RequestBody.create(contentType, file);
            // 将RequestBody封装成MultipartBody.Part类型（同样是okhttp的）
            MultipartBody.Part part = MultipartBody.Part.
                    createFormData(key, file.getName(), requestBody);
            // 添加进集合
            parts.add(part);
        }
        return parts;
    }

    public static MultipartBody.Part file2Part(String key, String filePaths, MediaType contentType) {
        File file = new File((String) filePaths);
        // 根据类型及File对象创建RequestBody（okhttp的类）
        RequestBody requestBody = RequestBody.create(contentType, file);
        // 将RequestBody封装成MultipartBody.Part类型（同样是okhttp的）
        MultipartBody.Part part = MultipartBody.Part.
                createFormData(key, file.getName(), requestBody);
        // 添加进集合
        return part;
    }

    public static void putDefultData(Context context, HashMap params) {
        params.put("userid", RequestBody.create(ServiceUtil.MULTIPART, PreferencesUtil.getString(context, PreferencesUtil.USER_ID)));
        String deviceId = Utils.getDeviceId(MyApplication.getInstance());
        params.put("deviceId", RequestBody.create(ServiceUtil.MULTIPART, deviceId));
        params.put("platform", RequestBody.create(ServiceUtil.MULTIPART, Constant.ANDROID_CHANNEL));
    }
}
